Passed
Pull Request — master (#19)
by Muhammad Dyas
01:38
created

TaskHandler.updatePollMessage   A

Complexity

Conditions 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 1
1
import {PollState, taskEvent} from '../helpers/interfaces';
2
import {callMessageApi} from '../helpers/api';
3
import {getStateFromCardName} from '../helpers/state';
4
import PollCard from '../cards/PollCard';
5
6
export default class TaskHandler {
7
  event: taskEvent;
8
9
  public constructor(event: taskEvent) {
10
    this.event = event;
11
  }
12
13
  async process(): Promise<void> {
14
    switch (this.event.action) {
15
      case 'close_poll':
16
        const currentState = await this.getStateFromMessageId();
17
        if (!currentState.closedTime || currentState.closedTime > Date.now()) {
18
          currentState.closedTime = Date.now();
19
        }
20
        const apiResponse = await this.updatePollMessage(currentState);
21
        if (apiResponse?.status !== 200) {
22
          throw new Error('Error when closing message');
23
        }
24
        break;
25
      default:
26
        console.log('unknown task');
27
    }
28
  }
29
30
  async getStateFromMessageId(): Promise<PollState> {
31
    const request = {
32
      name: this.event.id,
33
    };
34
    const apiResponse = await callMessageApi('get', request);
35
    const currentState = getStateFromCardName(apiResponse.data!.cardsV2?.[0].card ?? {});
36
    if (!currentState) {
37
      throw new Error('State not found');
38
    }
39
    return JSON.parse(currentState) as PollState;
40
  }
41
42
  async updatePollMessage(currentState: PollState) {
43
    const cardMessage = new PollCard(currentState).createMessage();
44
    const request = {
45
      name: this.event.id,
46
      requestBody: cardMessage,
47
      updateMask: 'cardsV2',
48
    };
49
    return await callMessageApi('update', request);
50
  }
51
}
52